package com.simu.towercrane.fragments;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVRelation;
import com.avos.avoscloud.FindCallback;
import com.baidu.navi.activity.RouteGuideDemo;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.simu.towercrane.R;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

public class FragmentBusinessDetils extends BaseFragmentTwo{
	View view=null;
	AVQuery<AVObject> query;
	int currentWhere;
	private ArrayList<String> listImage = new ArrayList<String>();
	private List<Map<String, Object>> mList;
	private double latitude = 0.0;
	private double longitude = 0.0;
	private static final double EARTH_RADIUS = 6378137;
	private ImageLoader mImageLoader;
	private ImageView IvImage;
	private ImageView IvAuthentication;
	private TextView TvbusinessName;
	private TextView TvSummary;
	private TextView TvConnect;
	private TextView TvAddress;
	private TextView TvDistance;
	private TextView TvFieldType;
	private TextView TvChannelType;
	private String addr;
	 @Override
	    public View onCreateView(LayoutInflater inflater, ViewGroup container,
	            Bundle savedInstanceState) {
		 mImageLoader = ImageLoader.getInstance();
		 if(view==null){
		 		Log.d("fragmentLife", "FragmentTwoonCreateView");
		 		view=inflater.inflate(R.layout.fragment_business_detials, null);
		 }
		 Tool.destroyParent(view);
			Intent intent = getActivity().getIntent();
			String objectID = intent.getStringExtra("objectID");
			SharedPreferences SP = getActivity().getSharedPreferences("user", 0);
			latitude = Double.valueOf(SP.getString("latitude", "0")).doubleValue();
			longitude = Double.valueOf(SP.getString("lontitude", "0"))
					.doubleValue();
			addr = SP.getString("addr", "");
			addproduct(objectID);
		 Tool.destroyParent(view);
		 return view;		 
	 }
	 
	 
	 public void addproduct(String objectID) {
		 	
			query = new AVQuery<AVObject>("Vendor");
			query.whereEqualTo("objectId", objectID);
			query.findInBackground(new FindCallback<AVObject>() {

				@Override
				public void done(List<AVObject> list, AVException arg1) {
					// TODO Auto-generated method stub
					mList = new ArrayList<Map<String, Object>>();
					mList.clear();
					if (list != null) {

						for (int i = 0; i < list.size(); i++) {
							currentWhere = list.size();
							final HashMap<String, Object> map = new HashMap();
							map.clear();

							AVObject parent = list.get(i);
							//parent.getString("name");

							AVRelation<AVObject> avRelation = parent
									.getRelation("image");
							
							AVQuery<AVObject> avQuery = avRelation.getQuery();
							avQuery.findInBackground(new FindCallback<AVObject>() {

								@Override
								public void done(List<AVObject> arg0,
										AVException arg1) {

									listImage.clear();
									if(arg0!=null)
									{
									for (int k = 0; k < arg0.size(); k++) {
										AVObject avobject = arg0.get(k);
										
										AVFile avFile = avobject.getAVFile("image");
										String url = avFile.getUrl();
										listImage.add(url);
										if(k==0)
										{
											map.put("url", url);
										}

									}
									map.put("urls", listImage);
									}
									
								}
							});
								
							AVRelation<AVObject> avRelationparams = parent
									.getRelation("fieldType");
							AVQuery<AVObject> avQueryparams = avRelationparams
									.getQuery();
							avQueryparams
									.findInBackground(new FindCallback<AVObject>() {

										@SuppressWarnings("unchecked")
										@Override
										public void done(List<AVObject> arg0,
												AVException arg1) {
											if(arg0!=null)
											{
											List Type=new ArrayList<String>();
											String fieldTypeName=null;
											for (int k = 0; k < arg0.size(); k++) {
//												map.put("fieldTypeName"+"k",
//														arg0.get(k).get("fieldType"));
												
												Type.add(arg0.get(k).getString("fieldName"));
												
												

											}
											for(int j=0;j<Type.size();j++)
											{
												if(j==0){
													fieldTypeName=Type.get(j).toString();
												}
												else{
													fieldTypeName=Type.get(j).toString()+"\t\t\t"+fieldTypeName;
												}
											}
											map.put("fieldTypeName", fieldTypeName);
											}
											initView(map);

										}
									});
							
							
							AVRelation<AVObject> avRelationparamschannel = parent
									.getRelation("channelType");
							AVQuery<AVObject> avQueryparamschannel  = avRelationparamschannel
									.getQuery();
							avQueryparamschannel
									.findInBackground(new FindCallback<AVObject>() {

										@Override
										public void done(List<AVObject> arg0,
												AVException arg1) {
											if(arg0!=null)
											{
											List Type=new ArrayList<String>();
											String channelTypeName = null;
											for (int k = 0; k < arg0.size(); k++) {
//												map.put("channelTypeName"+"k",
//														arg0.get(k).get("channelName"));
												
												
												Type.add(arg0.get(k).getString("channelName"));
											
												

											}
											for(int j=0;j<Type.size();j++)
											{
												if(j==0){
													channelTypeName=Type.get(j).toString();
												}
												else{
												channelTypeName=Type.get(j).toString()+"\t\t\t"+channelTypeName;
												}
											}
											map.put("channelTypeName", channelTypeName);
											}
											initView(map);

										}
									});
							
							
							
							map.put("vendorAddress", list.get(i).get("address"));//地址
							Object Tag=list.get(i).get("tag");//认证
							
							@SuppressWarnings("unchecked")
							ArrayList<String> tag=(ArrayList)Tag;
							if(tag!=null)
							{
								
								map.put("vendorAuthentication", "certified");
							}
							else{
								map.put("vendorAuthentication", "NOTcertified");
							}
							
							map.put("vendorName", list.get(i).get("vendorName"));
							double latitudevendor;
							double longitudevendor;
							if(list.get(i).getAVGeoPoint("location")!=null)
							{
							latitudevendor=list.get(i).getAVGeoPoint("location").getLatitude();
							longitudevendor=list.get(i).getAVGeoPoint("location").getLongitude();
							}
							else{
								latitudevendor=latitude;
								longitudevendor=longitude;
							
							}
							double vendorDistance=DistanceOfTwoPoints(latitude,longitude,latitudevendor,longitudevendor);
							int vendordistance=(int)vendorDistance;
							if (vendorDistance<1000)
							{
								map.put("vendorlocation", vendordistance+"M");
							}
							else{
								map.put("vendorlocation", vendordistance/1000+"KM");
							}
							
							
							
							
							
							

							map.put("summary", list.get(i).getString("summary"));
							map.put("connect",list.get(i).getString("contact"));
							map.put("tel", list.get(i).get("tel"));
							
							
							map.put("latitude", latitude);
							map.put("longitude", longitude);
							map.put("addr", addr);
							map.put("address", list.get(i).getString("vendorAddress"));
							map.put("latitudevendor", latitudevendor);
							map.put("longitudevendor", longitudevendor);
							
							
							

						}

					}

				}
			});

		}
		 
		 
	 @SuppressWarnings("rawtypes")
	public void initView(final HashMap<String, Object> map) {
		 
		   	 IvImage=(ImageView)view.findViewById(R.id.iv_business_image);
			 IvAuthentication=(ImageView)view.findViewById(R.id.iv_businsiness_muAuthentication);
			 TvbusinessName=(TextView)view.findViewById(R.id.tv_business_name);
			 TvSummary=(TextView)view.findViewById(R.id.tv_busniss_detail);
			 TvConnect=(TextView)view.findViewById(R.id.tv_busniess_connectpeple);
			 TvAddress=(TextView)view.findViewById(R.id.tv_business_companyaddress);
			 TvDistance=(TextView)view.findViewById(R.id.tv_business_distance);
			 TvChannelType=(TextView)view.findViewById(R.id.tv_business_business_channelType);
			 TvFieldType=(TextView)view.findViewById(R.id.tv_business_business_fieldType);			
			String url=map.get("url")+"";
			mImageLoader.displayImage( url, IvImage);
			TvbusinessName.setText(map.get("vendorName")+"");
			TvSummary.setText(map.get("summary")+"");
			TvConnect.setText(map.get("tel")+"");
			TvAddress.setText(map.get("vendorAddress")+"");
			TvDistance.setText(map.get("vendorlocation")+"");
			TvFieldType.setText(map.get("fieldTypeName")+"");
			TvChannelType.setText(map.get("channelTypeName")+"");
			if((map.get("vendorAuthentication")+"").equals("certified"))
			{
				IvAuthentication.setVisibility(View.VISIBLE);
			}
			
			
			final String tel=map.get("tel")+"";
			
             TvConnect.setOnClickListener(new OnClickListener(
            		 ) {
				
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					 Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+tel));  
		             startActivity(intent); 
				}
			});
             TvDistance.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					Intent intent = new Intent();
					intent.setClass(getActivity(), RouteGuideDemo.class);
					intent.putExtra("startlatitude", map.get("latitude") + "");
					intent.putExtra("startlongitude", map.get("longitude") + "");
					intent.putExtra("endlatitude", map.get("latitudevendor") + "");
					intent.putExtra("endlongitude", map.get("longitudevendor") + "");
					intent.putExtra("startName", map.get("addr") + "");
					intent.putExtra("endNamge", map.get("vendorAddress") + "");
					// intent.putExtra("objectID", getId());
					getActivity().startActivity(intent);
				}
			});
	 }
		 
	 
	 
		public void getlocation(){
			 LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
				if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
					Location location = locationManager
							.getLastKnownLocation(LocationManager.GPS_PROVIDER);
					if (location != null) {
						latitude = location.getLatitude();
						longitude = location.getLongitude();
					} else {
						LocationListener locationListener = new LocationListener() {

							// Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
							@Override
							public void onStatusChanged(String provider, int status,
									Bundle extras) {

							}

							// Provider被enable时触发此函数，比如GPS被打开
							@Override
							public void onProviderEnabled(String provider) {

							}

							// Provider被disable时触发此函数，比如GPS被关闭
							@Override
							public void onProviderDisabled(String provider) {

							}

							// 当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
							@Override
							public void onLocationChanged(Location location) {
								if (location != null) {
									Log.e("Map",
											"Location changed : Lat: "
													+ location.getLatitude() + " Lng: "
													+ location.getLongitude());
													latitude = location.getLatitude(); // 经度
									longitude = location.getLongitude(); // 纬度
								}
							}
						};
						locationManager.requestLocationUpdates(
								LocationManager.NETWORK_PROVIDER, 1000, 0,
								locationListener);
						Location location1 = locationManager
								.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
						if (location1 != null) {
							latitude = location1.getLatitude(); // 经度
							longitude = location1.getLongitude(); // 纬度
						}
					}
				}
		 }
		
		 public static double rad(double d){
			 return d * Math.PI / 180.0;
		 }
		 public static double DistanceOfTwoPoints(double lat1,double lng1,   
	             double lat2,double lng2) {  
	        double radLat1 = rad(lat1);  
	        double radLat2 = rad(lat2);  
	        double a = radLat1 - radLat2;  
	        double b = rad(lng1) - rad(lng2);  
	        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)  
	                + Math.cos(radLat1) * Math.cos(radLat2)  
	                * Math.pow(Math.sin(b / 2), 2)));  
	        s = s * EARTH_RADIUS;  
	        s = Math.round(s * 10000) / 10000;  
	        return s;  
	    }  
}
